<template>
  <div class="studentDetail">
    <div class="studentDetail-header">
      <div class="studentDetail-headertop">
        {{ '2024-2025学年学业情况' }}
        <span>待完成</span>
      </div>
      <el-breadcrumb separator="/" class="studentDetail-headerbottom">
        <el-breadcrumb-item :to="{ path: '/student/studentSituation' }">任务列表</el-breadcrumb-item>
        <el-breadcrumb-item>填报详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="studentDetail-main">
      <div class="studentDetail-main-top">
        <div style="font-weight: 550; font-size: 25px;">
          {{ '2024-2025学年学业情况' }}</div>
        <div style="color: #8a8a8b; text-align: center; margin: 26px 0; font-size: 18px;;">
          {{ '时间：2025/06/11-2025/07/11' }}</div>
      </div>
      <el-form
        ref="studentDetailFormRef"
        class="studentDetailForm"
        :model="studentDetailForm"
        :rules="studentDetailrules"
        label-width="150px"
        label-position="left"
      >
      
        <!-- 基本学业 -->
        <div class="studentDetail-main-subject">
          <div class="studentDetailTitle">基本学业</div>
          <el-form-item label="考试" prop="examLevel">
            <el-radio-group v-model="studentDetailForm.examLevel">
              <el-radio value="四级" @click="exam=4">四级
                <el-input v-if="exam==4" v-model="studentDetailForm.examscore" style="margin-left: 15px;width: 100px;" placeholder="请输入四级最高成绩"/>
              </el-radio>
              <el-radio value="六级" @click="exam=6">六级
                <el-input v-if="exam==6" v-model="studentDetailForm.examscore" style="margin-left: 15px;width: 100px;" placeholder="请输入六级最高成绩"/>
              </el-radio>
              <el-radio value="无" @click="examscore=0">无</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="奖学金情况" prop="scholarship">
            <el-input v-model="studentDetailForm.scholarship" type="textarea" placeholder="请输入" maxlength="50" show-word-limit autosize/>
          </el-form-item>
          <el-form-item label="政治面貌" prop="politicalAppearance">
            <el-select v-model="studentDetailForm.politicalAppearance" placeholder="请选择政治面貌" class="">
              <el-option label="党员" value="党员" />
              <el-option label="共青团员" value="共青团员" />
              <el-option label="群众" value="群众" />
            </el-select>
          </el-form-item>
          <el-form-item label="加权绩点" prop="grades">
            <el-input v-model="studentDetailForm.grades" placeholder="请输入加权绩点"/>
          </el-form-item>
          <el-form-item label="志愿时长" prop="volunteerDuration">
            <el-input v-model="studentDetailForm.volunteerDuration" placeholder="请输入本学年志愿时长（单位：小时）"/>
          </el-form-item>
        </div>

        <!-- 比赛 -->
        <div class="studentDetail-main-subject">
          <div class="studentDetailTitle">比赛</div>
          <el-form-item label="获奖情况" prop="competitionDescription">
            <el-input v-model="studentDetailForm.competitionDescription" type="textarea" autosize
            placeholder="请输入比赛名称和获奖名次情况，部分非国家级比赛请写明是否为区域赛或赛区范围（如：全国大学生物联网设计竞赛（华北赛区）），并在下方上传证书图片" maxlength="50" show-word-limit/>
          </el-form-item>
          <el-form-item label="获奖证书" prop="competitionPath">
            <el-upload
              ref="competitionUpload"
              class="set-upload"
              drag
              :file-list="competitionFiles"
              :auto-upload="false"
              multiple
              name="file"
               @change="handleCompetitionChange"
            >
              <el-icon class="el-icon--upload">+</el-icon>
              <div class="el-upload__text">
                点击或拖拽文件到此处上传
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 论文 -->
        <div class="studentDetail-main-subject">
          <div class="studentDetailTitle">论文</div>
          <el-form-item label="论文情况" prop="paperDescription">
            <el-input v-model="studentDetailForm.paperDescription" type="textarea" autosize
            placeholder="请输入刊物名称、类别和获奖名次情况（如：CCF A类英文期刊） 并在下方上传证明图片" maxlength="50" show-word-limit/>
          </el-form-item>
          <el-form-item label="图片证明" prop="paperPath">
            <el-upload
              ref="paperUpload"
              class="set-upload"
              drag
              :file-list="paperFiles"
              :auto-upload="false"
              multiple
              name="file"
              @change="handlePaperChange"
            >
              <el-icon class="el-icon--upload">+</el-icon>
              <div class="el-upload__text">
                点击或拖拽文件到此处上传
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 科研成果 -->
        <div class="studentDetail-main-subject">
          <div class="studentDetailTitle">科研成果</div>
          <el-form-item label="授权的发明专利情况" prop="scientificResearchDescription" label-width="230px" style="margin-left: -110px;">
            <el-input v-model="studentDetailForm.scientificResearchDescription" type="textarea" autosize
            placeholder="请输入名称和专利排名（除去指导教师的实际排名）" maxlength="50" show-word-limit/>
          </el-form-item>
          <el-form-item label="软件著作权情况" prop="Copyright" label-width="200px" style="margin-left: -50px;">
            <el-input v-model="studentDetailForm.Copyright" type="textarea" autosize
            placeholder="请输入名称和专利排名（除去指导教师的实际排名）若申请人非个人，请上传教师提供的纸质证明" maxlength="50" show-word-limit/>
          </el-form-item>
          <el-form-item label="纸质证明" prop="scientificResearchPath">
            <el-upload
              ref="researchUpload"
              class="set-upload"
              drag
              :file-list="researchFiles"
              :auto-upload="false"
              multiple
              name="file"
              @change="handleResearchChange"
            >
              <el-icon class="el-icon--upload">+</el-icon>
              <div class="el-upload__text">
                点击或拖拽文件到此处上传
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 违纪 -->
        <div class="studentDetail-main-subject">
          <div class="studentDetailTitle">违纪</div>
          <el-form-item label="违纪情况" prop="disciplinaryText">
            <el-input v-model="studentDetailForm.disciplinaryText" type="textarea" autosize
            placeholder="请输入本学年违纪情况" maxlength="50" show-word-limit/>
          </el-form-item>
        </div>
        <el-form-item style="margin: auto;">
          <el-button type="primary" @click="submitForm(studentDetailFormRef)"
          style="width: 40%; margin: 20px; margin-left: 15%;min-width: 200px; height: 40px; font-size: 22px;border-radius: 10px; background-color: #f00a0a;"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useStudentDetailStore } from '@/stores/student/studentDetail'
import { post } from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'


const route = useRoute()
const studentDetailStore = useStudentDetailStore()

onMounted(() => {
  if (window.location.href.indexOf("#reloaded") == -1) {
    location.href = location.href + "#reloaded"
    location.reload()
  }
})

// 添加上传组件的引用
const competitionFiles = ref([])
const paperFiles = ref([])
const researchFiles = ref([])

// 文件变更处理函数
const handleCompetitionChange = (file, fileList) => {
  competitionFiles.value = fileList
}

const handlePaperChange = (file, fileList) => {
  paperFiles.value = fileList
}

const handleResearchChange = (file, fileList) => {
  researchFiles.value = fileList
}


const questionnaireId = route.query.id

let exam = ref(undefined)
// 表单数据
const studentDetailFormRef = ref()
const studentDetailForm = reactive({
  examLevel:'',
  examscore:'' || 0,
  scholarship: '',
  politicalAppearance:'',
  grades:'',
  volunteerDuration:'',
  competitionDescription:'',
  competitionPath:'',
  paperDescription:'',
  paperPath:'',
  scientificResearchDescription:'',
  Copyright:'',
  scientificResearchPath:'',
  disciplinaryText:'',
  files:{
    fileType:'',
    path:'',
  }
  
})

// 表单验证
const studentDetailrules = reactive({
  jxjqk: [
    { required: true, message:"请填写奖学金情况" ,trigger: 'blur' },
  ],
  examLevel: [
    {
      required: true,
      message: '请填写考试情况',
      trigger: 'blur',
    },
  ],
  scholarship: [
    { required: true,message: '请输入奖学金情况',trigger: 'blur' },
  ],
  politicalAppearance: [
    { required: true,message: '请选择政治面貌',trigger: 'blur' },
  ],
  grades: [
    { required: true,message: '请填写加权绩点',trigger: 'blur' },
  ],
  volunteerDuration: [
    { required: true,message: '请填写志愿时长',trigger: 'blur' },
  ],
  competitionDescription: [
    { required: true,message: '请填写获奖情况',trigger: 'blur' },
  ],
  paperDescription: [
    { required: true,message: '请填写论文情况',trigger: 'blur' },
  ],
  scientificResearchDescription: [
    { required: true,message: '请填写授权的发明专利情况',trigger: 'blur' },
  ],
  Copyright: [
    { required: true,message: '请填写软件著作权情况',trigger: 'blur' },
  ],
  disciplinaryText: [
    { required: true,message: '请填写违纪情况',trigger: 'blur' },
  ],
})


// 提交表单
const submitForm = async (formEl) => {
  try{
    if (!formEl) return
    await formEl.validate()

    // 构造 JSON 对象
    const jsonData = ref({
      questionnaireId:questionnaireId,
      examLevel: studentDetailForm.examLevel,
      examScore: studentDetailForm.examscore,
      scholarship: studentDetailForm.scholarship,
      politicalAppearance: studentDetailForm.politicalAppearance,
      grades: studentDetailForm.grades,
      volunteerDuration: studentDetailForm.volunteerDuration,
      competitionDescription:studentDetailForm.competitionDescription,
      competitionPath:[],
      paperDescription:studentDetailForm.paperDescription,
      paperPath:[],
      scientificResearchDescription:studentDetailForm.scientificResearchDescription,
      Copyright:studentDetailForm.Copyright,
      scientificResearchPath:[],
      disciplinaryText:studentDetailForm.disciplinaryText,
      graduationText:''
    })

    // const formData = new FormData()
    // formData.append('form', JSON.stringify(jsonData))

    // // 添加比赛证书文件
    // if (competitionFiles.value.length > 0) {
    //   competitionFiles.value.forEach((file, index) => {
    //     formData.append(`files`, file.raw)
    //     formData.append('fileTypes', 'competitionDescription')
    //   })
    // }
    
    // // 添加论文证明文件
    // if (paperFiles.value.length > 0) {
    //   paperFiles.value.forEach((file, index) => {
    //     formData.append(`files`, file.raw)
    //     formData.append('fileTypes', 'paperDescription')
    //   })
    // }
    
    // // 添加科研成果文件
    // if (researchFiles.value.length > 0) {
    //   researchFiles.value.forEach((file, index) => {
    //     formData.append(`files`, file.raw)
    //     formData.append('fileTypes', 'scientificResearchDescription')
    //   })
    // }

    // // 调试：检查 FormData 内容
    // for (let [key, value] of formData.entries()) {
    //   console.log(key, value)
    // }

    console.log(localStorage.getItem('token'))
    const formData1 = new FormData()
    const formData2 = new FormData()
    const formData3 = new FormData()
    
    // 上传文件
    if (competitionFiles.value.length > 0) {
      competitionFiles.value.forEach((file) => {
        formData1.append('file',file.raw)
      })
      const response1 = await post('/student/file',formData1)
      jsonData.value.competitionPath = response1.data
    }
    // 添加论文证明文件
    if (paperFiles.value.length > 0) {
      paperFiles.value.forEach((file) => {
        formData2.append('file',file.raw)
      })
      const response2 = await post('/student/file',formData2)
      jsonData.value.paperPath = response2.data
    }
    
    // 添加科研成果文件
    if (researchFiles.value.length > 0) {
      researchFiles.value.forEach((file) => {
        formData3.append('file',file.raw)
      })
      const response3 = await post('/student/file',formData3)
      jsonData.value.scientificResearchPath = response3.data
    }

    console.log(jsonData.value)
    await post('/student/edits', jsonData)

    // 6. 成功后提交
    await post(`/student/submit?questionnaireId=${questionnaireId}`)

    ElMessage.success('提交成功！')
  }catch(error){
    console.log(error)
    ElMessage.error('提交失败，请检查表单')
  }
}
</script>

<style scoped>
.studentDetail {
  width: 100%;
  height: 100%;
  position: relative;
  .studentDetail-header {
    width: 100%;
    height: 16vh;
    position: sticky;
    top: 0px;
    .studentDetail-headertop {
      width: 100%;
      height: 8vh;
      background-color: #fff;
      border-top: 1px solid #c9c9ca;
      line-height: 8vh;
      font-size: 18px;
      font-weight: 700;
      padding: 0 30px;
      span {
        color: #b31219;
        font-size: 22px;
        font-weight: normal;
        margin-left: 20px;
      }
    }
    .studentDetail-headerbottom {
      width: 100%;
      height: 8vh;
      line-height: 8vh;
      padding: 0 40px;
      font-size: 18px;
      :deep(.el-breadcrumb__inner) {
        font-weight: normal;
        color: #7f7f7f;
      }
    }
  }

  .studentDetail-main {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .studentDetailForm {
      width: 90%;
      .studentDetail-main-subject {
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #fff;
        padding-top: 20px;
        margin: 20px 0;
      }
    }
  }
}
.studentDetailTitle {
  font-weight: 500;
  font-size: 22px;
  margin-bottom: 15px;
  margin-left: -50%;
}
.el-form-item {
  width: 70%;
  margin-bottom: 30px;
  margin-left: 50px;
}
:deep(.el-form-item__label) {
  font-size: 18px;
  color: black;
  margin-left: 30px;
}
:deep(.el-radio__label) {
  font-size: 15px;
  color: #7f7f7f;
}
/* .el-radio {
  margin-right: 40px;
} */
/* :deep(.el-input__wrapper) {
  background-color: #f2f3f5;
} */

:deep(.el-textarea),
:deep(.el-input),
:deep(.el-select)
 {
  max-width: 300px;
  min-width: 200px;
}
.set-upload {
  width: 100%;
}
:deep(.el-upload-dragger){
  max-width: 300px;
  min-width: 200px;
  padding: 0px;
}
:deep(.el-textarea__inner),
:deep(.el-select__wrapper),
:deep(.el-upload-dragger),
:deep(.el-input__wrapper) {
  background-color: #f2f3f5;
}
</style>